package com.leyou.user.service;

import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public Boolean check(String data, Integer type) {

        User user = new User();
        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
        }
        return this.userMapper.selectCount(user)!=1;
    }


    static final String KEY_PREFIX = "user:code:phone:";
    public void sendCode(String phone) {
        //发送的是验证码？？？？？


        //指定长度生成一个验证码
        String verifyCode = NumberUtils.generateCode(7);
        Map<String, String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",verifyCode);

        amqpTemplate.convertAndSend("ly.sms.exchange","sms.verify.code",msg);



        //把验证码保存到redis中,只保存5min
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,verifyCode,5, TimeUnit.MINUTES);

    }

    public Boolean register(User user, String code) {

        //首先要校验验证码

        //不一定有值
        String storeVerifyCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());

        //判断验证码是否正确
        if (!code.equals(storeVerifyCode)){

            return false;
        }

        //对用户进行加密，MD5加密

        //随机生成一个盐值
        String salt = CodecUtils.generateSalt();

        user.setSalt(salt);

        //根据用户原来的面吗以及盐值，生成最终的密码
        user.setPassword(CodecUtils.md5Hex(user.getPassword(),salt));

        user.setCreated(new Date());

        //注册时验证码校验完毕，删除redis的校验码
        this.redisTemplate.opsForValue().set(KEY_PREFIX+user.getPhone(),"",1,TimeUnit.NANOSECONDS);


        return this.userMapper.insertSelective(user)==1;
    }


    //先根据用户名查询对应的用户，获取盐值，以及用户输入的内容，做整合加密与数据库中存储的密码比较
    public User queryUser(String username, String password) {

        User record = new User();
        record.setUsername(username);

        //执行查询并获取差的结果
        User user = this.userMapper.selectOne(record);

        //比对
        if(null==user){
            return null;
        }

        //使用户查询到的密码和用户输入的密码进行加密处理后比对
        if (user.getPassword().equals(CodecUtils.md5Hex(password,user.getSalt()))){
            return user;
        }

        return null;
    }
}
